package cn.edu.cug.cs.gtl.apps.ui.actions;

import cn.edu.cug.cs.gtl.apis.render.Render;
import cn.edu.cug.cs.gtl.apis.render.viewers.Viewer;
import cn.edu.cug.cs.gtl.apis.ui.AbstractApplication;
import cn.edu.cug.cs.gtl.apis.render.nodes.Node;
import cn.edu.cug.cs.gtl.apis.ui.modeller.ModellerApp;

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

public class OpenIVFileActionListener implements ActionListener {
    AbstractApplication theApp = null;

    public OpenIVFileActionListener(AbstractApplication theApp) {
        this.theApp = theApp;
    }

    @Override
    public void actionPerformed(ActionEvent e) {

        final FileFilter ivFileFilter = new IVFileFilter();

        final JFileChooser ivFileChooser = new JFileChooser(
                //new File(SoPreferences.getValue("OIVJHOME") + File.separator + "data" + File.separator + "models"));
                new File(System.getProperty("user.dir")) );
        ivFileChooser.setFileFilter(ivFileFilter);
        ivFileChooser.removeChoosableFileFilter(ivFileChooser.getAcceptAllFileFilter());

        if ( ivFileChooser.showOpenDialog(null) != JFileChooser.APPROVE_OPTION )
            return;
        String fileName = ivFileChooser.getSelectedFile().getAbsolutePath();
        Node node = null;
        try {
            node = getRender().loadFile(fileName);
        }
        catch (IOException exception){
            exception.printStackTrace();
        }
        if(node==null) return;

        getRender().setSceneGraph(node);
        getViewer().viewAll();
    }

    public Render getRender() {
        return ((ModellerApp)theApp).getModel3dUIApp().getRender();
    }

    public Viewer getViewer(){
        return ((ModellerApp)theApp).getModel3dUIApp().getViewer();
    }
}
